package com.beecloud.learning.charpter.three;

/**
 * Created with IntelliJ IDEA.
 * User: hengsun
 * Date: 3/27/17
 * Time: 2:51 PM
 * Description:
 */
public class NoVisibility {


    private static class ReaderThread extends Thread{
        private Data data;

        ReaderThread(Data data) {
            this.data = data;
        }

        @Override
        public void run() {
            while (!data.ready) {
                System.out.println("reader thread yield......");
                Thread.yield();
            }

            System.out.println(String.format("number is %d", data.number));
        }
    }

    private static class WriteThread extends Thread {
        private  Data data;

        WriteThread(Data data) {
            this.data = data;
        }
        @Override
        public void run() {
            System.out.println("Prepare to write  value....");
            data.ready = true;
            //try {
            //    Thread.sleep(2);
            //} catch (InterruptedException e) {
            //    e.printStackTrace();
            //}
            data.number = 42;
        }
    }



    public static void main(String[] args) throws InterruptedException {
        Data data = new Data();
        new ReaderThread(data).start();
        new WriteThread(data).start();
    }

    private static class Data {
        public   int number;
        public   boolean ready;
    }
}


